package edu.mtu.citizenscience.cs.notepad.activity.noteslist.note.photo;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.content.Intent;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;

import edu.mtu.citizenscience.cs.notepad.NPActivity;
import edu.mtu.citizenscience.cs.notepad.activity.R;
import edu.mtu.citizenscience.cs.notepad.model.ModelNote;
import edu.mtu.citizenscience.cs.notepad.model.note.ModelImage;
import edu.mtu.citizenscience.cs.utils.Message;
import edu.mtu.citizenscience.cs.utils.NewFeatureSupport;
import edu.mtu.citizenscience.cs.utils.Utils;
/**
 * @author Corbin Uselton <corbinu@cwuselto@mtu.edu>
 * @copyright (c) 2012 MichiganTech <http://www.mtu.edu>
 * @since 1.0
 * 
 * Photo Activity Responsible taking, viewing and deleting a note photo
 */
public class PhotoActivity extends NPActivity {
	// reference vars for photo take activity
	private static final int ACTION_TAKE_PHOTO = 1;
	
	// The model of the note the photos get attached to
	private ModelNote note;
	// the image currently being viewed if any
	private ModelImage image;
	
	/**
	 * Photo Activity creation handler
	 * 
	 * @param   savedInstanceState - Bundle - Bundle with launch info
	 * @return	void
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.activity_photo);
		
		// try to get the note id from the intent bundle
		long noteId = this.getIntent().getLongExtra(ModelNote.NOTE_ID, -1);
		
		// check to see if got a note id
		if (noteId > -1)
		{
			// set the note model to the model with the given note id
			this.note = new ModelNote(this, noteId).find();
		}
		else
		{
			// no note to attach the photo to so finish the activity
			this.finish();
		}
		
		// try to get the image id from the intent bundle
		long imageId = this.getIntent().getLongExtra(ModelImage.IMAGE_ID, -1);
		
		// check to see if got a image id
		if (imageId > -1)
		{
			// set the image model to the model with the given image id
			this.image = new ModelImage(this, imageId).find();
			
			// get the size of the current android display
			Point displaySize = NewFeatureSupport.getDisplaySize(this.getWindowManager().getDefaultDisplay());
			
			// set the image preview to the passed image scaled to the display size
			this.aq.id(R.id.imagePreview).image(this.image.getPath(), true, true, displaySize.x, 0).visible();
		}
		else
		{
			// no image passed so take a new image
			this.getImage();
		}
		
		// set remove image button click handler to removeImage
		aq.id(R.id.removeImageButton).clicked(this, "removeImage");
	}
	
	/**
	 * Photo Activity activity result handler
	 * is called when a response is received from a 
	 * take photo intent launched from this activity
	 * 
	 * @param   requestCode - int - The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
	 * @param	resultCode - int - The integer result code returned by the child activity through its setResult().
	 * @param	data  - Intent - An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
	 * @return	void
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		// check to see if the take photo task was successful
		if (resultCode == RESULT_OK) 
		{
			// close the activity
			this.finish();
		}
		else
		{
			// did not take photo so remove the tmp image file and the image model
			this.removeImage();
		}
	}
	
	/**
	 * Get a new image for the note by creating a 
	 * new image model and file and then launching an
	 * intent for image capture
	 * 
	 * @param   void
	 * @return	void
	 */
	public void getImage()
	{
		// check to make sure the device has a application to take images
		if (Utils.isIntentAvailable(this, MediaStore.ACTION_IMAGE_CAPTURE))
		{
			// check to make sure the device has writable external storage to store the photo on
			if (Utils.isExternalStorageWritable())
			{
				// get a new dir for storing note pad photos inside the standard CitSci files location
				File photoDir = new File(Utils.citsciFiles(this), "notepad/photo/");
				// make sure the photo dir and its parent dirs exist
				photoDir.mkdirs();
				
				try 
				{
					// create a new tmp jpg file in the photo dir with the current date time
					File imageFile = File.createTempFile(new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date()), ".jpg", photoDir);
					
					// create a new image model to store the image information in the DB
					this.image = new ModelImage(this);
					// set the image model path to the new image file
					this.image.setPath(imageFile.getAbsolutePath());
					// set the image model date to the current date time
					this.image.setDate(Calendar.getInstance().getTime());
					// set the images parent note
					this.image.setNote(this.note);
					// save the image model to the DB
					this.image.save();
					
					// add the image model to the parent notde
					this.note.getImages().add(image);
					// save the note
					this.note.save();
					
					// create a new image capture intnet and put the tmp file as the photo output and launch new activity for take photo result
					this.startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile)), ACTION_TAKE_PHOTO);
				} 
				catch (IOException e) 
				{
					Message.showMessage(this, "Error: Could not create file to save photo to");
				}
			}
			else
			{
				Message.showMessage(this, "Error: External storage is no writable");
			}
		}
		else
		{
			Message.showMessage(this, "Error: No application installed capable of taking pictures");
		}
	}
	
	/**
	 * Remove the current image form the file system and db
	 * 
	 * @param   void
	 * @return	void
	 */
	public void removeImage()
	{
		// delete the image model
		this.image.delete();
		
		// close the activity
		this.finish();
	}

}